/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fx.judge;

import beans.Judge;
import dao.DaoJudge;
import fx.Home;
import fx.menu.MenuController;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;

/**
 * FXML Controller class
 *
 * @author Jandrei
 */
public class JudgeController extends AnchorPane implements Initializable {

    Judge judge;
    DaoJudge dao;
    Home application;
    @FXML
    private ResourceBundle resources;
    @FXML
    private URL location;
    @FXML
    private Label lblErrorBJCP;
    @FXML
    private Label lblErrorEmail;
    @FXML
    private Label lblErrorName;
    @FXML
    private Label lblErrorPassword;
    @FXML
    private Label lblErrorRetype;
    @FXML
    private Button btnCancel;
    @FXML
    private Button btnSave;
    @FXML
    private TextField textBjcpId;
    @FXML
    private TextField textEmail;
    @FXML
    private PasswordField textPassword;
    @FXML
    private PasswordField textRetype;
    @FXML
    private TextField textName;

    @FXML
    void cancel(ActionEvent event) {
        MenuController menu;
        try {
            menu = (MenuController) application.replaceSceneContent("menu/menu.fxml", Home.MENUWIDTH, Home.MENUHEIGTH, "BJCP-Scoresheet");
            menu.setMessage("sucess", "Welcome " + Home.loggedUser.getName());
            menu.setApp(application);
        } catch (Exception ex) {
            Logger.getLogger(JudgeController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    void saveJudge(ActionEvent event) {

        String msgEmptyError = "Campo obrigatório";
        boolean save = true;

        if (textEmail.getText().trim().isEmpty()) {
            lblErrorEmail.setText(msgEmptyError);
            lblErrorEmail.setVisible(true);
            save = false;
        } else {
            String regex = "[A-Za-z0-9\\._-]+@[A-Za-z]+\\.[A-Za-z]+";
            if (!textEmail.getText().trim().matches(regex)) {
                lblErrorEmail.setText("This email is invalid.");
                lblErrorEmail.setVisible(true);
                save = false;
            }
        }
        if (textBjcpId.getText().trim().isEmpty()) {
            lblErrorBJCP.setText(msgEmptyError);
            lblErrorBJCP.setVisible(true);
            save = false;
        }
        if (textPassword.getText().trim().isEmpty()) {
            lblErrorPassword.setText(msgEmptyError);
            lblErrorPassword.setVisible(true);
            save = false;
        }
        if (textRetype.getText().trim().isEmpty()) {
            lblErrorRetype.setText(msgEmptyError);
            lblErrorRetype.setVisible(true);
            save = false;
        } else if (!textPassword.getText().trim().isEmpty() && !textPassword.getText().trim().equals(textRetype.getText().trim())) {
            lblErrorRetype.setText("The two passwords doesn't matches");
            lblErrorRetype.setVisible(true);
            save = false;
        }
        if (textName.getText().trim().isEmpty()) {
            lblErrorName.setText(msgEmptyError);
            lblErrorName.setVisible(true);
            save = false;
        }

        if (!save) {
            return;
        }

        judge = new Judge();
        judge.setEmail(textEmail.getText());
        judge.setName(textName.getText());
        judge.setSenha(textPassword.getText());
        judge.setBjcpId(textBjcpId.getText());
        dao = new DaoJudge();
        dao.save(judge);

        try {
            MenuController menu = (MenuController) application.replaceSceneContent("menu/menu.fxml", Home.MENUWIDTH, Home.MENUHEIGTH, "BJCP-Scoresheet");
            menu.setMessage("sucess", "Judge registered successfully!");
            menu.setApp(application);
        } catch (Exception ex) {
            Logger.getLogger(JudgeController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    final EventHandler<KeyEvent> emailEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorEmail.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> bjcpEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorBJCP.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> nameEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorName.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> passwordEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorPassword.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> retypeEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorRetype.setVisible(false);
            }
        }
    };

    @FXML
    void initialize() {
        assert btnSave != null : "fx:id=\"btnSave\" was not injected: check your FXML file 'Judge.fxml'.";
        assert textBjcpId != null : "fx:id=\"textBjcpId\" was not injected: check your FXML file 'Judge.fxml'.";
        assert textEmail != null : "fx:id=\"textEmail\" was not injected: check your FXML file 'Judge.fxml'.";
        assert textPassword != null : "fx:id=\"textPassword\" was not injected: check your FXML file 'Judge.fxml'.";
        assert textName != null : "fx:id=\"txtName\" was not injected: check your FXML file 'Judge.fxml'.";
        textBjcpId.setOnKeyPressed(bjcpEventHandler);
        textEmail.setOnKeyPressed(emailEventHandler);
        textName.setOnKeyPressed(nameEventHandler);
        textPassword.setOnKeyPressed(passwordEventHandler);
        textRetype.setOnKeyPressed(retypeEventHandler);
        try {
            FileInputStream saveImage = new FileInputStream(System.getProperty("user.dir") + "\\src\\fx\\css\\images\\save.png");
            Image imageSave = new Image(saveImage);
            btnSave.setGraphic(new ImageView(imageSave));
            FileInputStream cancelImage = new FileInputStream(System.getProperty("user.dir") + "\\src\\fx\\css\\images\\cancel.png");
            Image imageCancel = new Image(cancelImage);
            btnCancel.setGraphic(new ImageView(imageCancel));
        } catch (FileNotFoundException ex) {
            System.out.println("Image error");
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        initialize();
    }

    public void setApp(Home application) {
        this.application = application;
    }
}
